package com.magic.gre.ui.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.magic.gre.GREApp;
import com.magic.gre.R;
import com.magic.gre.adapter.ChooseUnitAdapter;
import com.magic.gre.base.activity.BaseMVPActivity;
import com.magic.gre.entity.ChooseUnitBean;
import com.magic.gre.mvp.contract.ChooseUnitContract;
import com.magic.gre.mvp.presenter.ChooseUnitPresenterImpl;
import com.magic.gre.utils.PermissonUtils;
import com.noname.lib_base_java.db.download.DowanloadDBManager;
import com.noname.lib_base_java.entity.MsgEvent;
import com.noname.lib_base_java.global.GlobalApplication;
import com.noname.lib_base_java.net.download.DownloadInfo;
import com.noname.lib_base_java.net.download.DownloadManager;
import com.noname.lib_base_java.net.download.FileUtil;
import com.noname.lib_base_java.util.L;
import com.noname.lib_base_java.util.ToastUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.zeroturnaround.zip.ZipUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

/**
 * Author: Lmoumou
 * Date: 2019-01-08 10:10
 * 文件名: ChooseUnitActivity
 * 描述:
 */
public class ChooseUnitActivity extends BaseMVPActivity<ChooseUnitPresenterImpl> implements ChooseUnitContract.View,
        DownloadManager.ProgressListener, ChooseUnitAdapter.OnItemClickListener {
    private static final String TAG = "ChooseUnitActivity";
    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.download_bt)
    Button downloadBt;

    public static void startThis(Context context, String thesaurusId) {
        Intent intent = new Intent(context.getApplicationContext(), ChooseUnitActivity.class);
        intent.putExtra("thesaurusId", thesaurusId);
        context.startActivity(intent);
    }

    private RxPermissions rxPermissions;
    private ChooseUnitAdapter adapter;
    private List<ChooseUnitBean> dataList = new ArrayList<>();
    private String thesaurusId;
    private DownloadInfo downloadInfo;
    private boolean done = false;
    private Handler handler = new Handler();
    private int servicePro = 0;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_choose_unit;
    }

    @Override
    protected ChooseUnitPresenterImpl creatPresenter() {
        return new ChooseUnitPresenterImpl(this);
    }

    @Override
    protected void netOverride() {

    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void handlerMsg(MsgEvent msgEvent) {
        super.handlerMsg(msgEvent);
        switch (msgEvent.getEvent()) {
            case MsgEvent.DOWANLOAD_PRO:
                servicePro = (int) msgEvent.get("pro");
                downloadBt.setText("正在下载" + servicePro + "%");
                break;
            case MsgEvent.DOWANLOAD_FINISH:
                DownloadInfo info = (DownloadInfo) msgEvent.get("DownloadInfo");
                downFinish(info);
                break;
        }
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        registerRxBus();
        rxPermissions = new RxPermissions(this);
        thesaurusId = getIntent().getStringExtra("thesaurusId");
        mSmartRefreshLayout.setEnableLoadMore(false);
        mSmartRefreshLayout.setEnableRefresh(false);

        String path = Environment.getExternalStorageDirectory() + File.separator + GlobalApplication.getContext().getPackageName() + File.separator + "Download" + File.separator + "downloadinfo.txt";
        File file = new File(path);
        if (file.exists()) {
            try {
                String content = FileUtil.readTxtFile(file);
                List<DownloadInfo> contentList = new Gson().fromJson(content, new TypeToken<List<DownloadInfo>>() {
                }.getType());

                for (DownloadInfo info : contentList) {
                    if (thesaurusId.equals(info.getThesaurus_id())) {
                        downloadInfo = info;
                        break;
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (downloadInfo != null && downloadInfo.getSavePath() != null && !TextUtils.isEmpty(downloadInfo.getSavePath())) {
            File filex = new File(downloadInfo.getSavePath());

            if (filex.exists()) {
                downloadInfo.setReadLength(filex.length());
            }


            if (downloadInfo.getContentLength() == downloadInfo.getReadLength()) {//下载完成
                this.done = true;
                downloadBt.setText("离线语音包已下载");
                downloadBt.setEnabled(false);
                downloadBt.setVisibility(View.GONE);
            } else if (downloadInfo.getReadLength() < downloadInfo.getContentLength()) {//继续下载
                this.done = false;
                downloadBt.setText("下载离线语音包");
                downloadBt.setEnabled(true);
            }
        } else {
            this.done = false;
            downloadBt.setText("下载离线语音包");
            downloadBt.setEnabled(true);
        }

        adapter = new ChooseUnitAdapter(this, dataList);
        adapter.setOnItemClickListener(this);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(adapter);
        mPresenter.pUnitList(thesaurusId);
    }

    @SuppressLint("CheckResult")
    @OnClick(value = {R.id.download_bt})
    protected void onClick(View view) {
        switch (view.getId()) {
            case R.id.download_bt:
                stopDownService();
                rxPermissions.request(PermissonUtils.READ_WRITE)
                        .subscribe(new Consumer<Boolean>() {
                            @Override
                            public void accept(Boolean aBoolean) throws Exception {
                                if (aBoolean) {
                                    downloadBt.setText("下载中...");
                                    mPresenter.pResourcesAddress(thesaurusId);
                                } else {
                                    ToastUtil.getInstance().showNormal(ChooseUnitActivity.this, "权限申请失败");
                                }
                            }
                        });
                break;
        }
    }

    @Override
    public void vUnitList(List<ChooseUnitBean> unitBeanList) {
        dataList.clear();
        dataList.addAll(unitBeanList);
        adapter.notifyDataSetChanged();
    }

    @SuppressLint("CheckResult")
    @Override
    public void vResourcesAddress(final DownloadInfo addressBean) {
        this.downloadInfo = addressBean;
        mPresenter.pDownload(addressBean, this);
    }

    @Override
    public void vLastUnit(String lastId, String unitId, String name) {
        WordsDetailsActivity.startThis(this, unitId, name, String.valueOf(lastId));
    }


    @Override
    public void vDownload(final DownloadInfo info) {
        super.vDownload(info);
        this.downloadInfo = info;
        if (done) {
            downFinish(info);
            hideLoadDialog();
        }
    }

    /**
     * 下载完成
     *
     * @param info
     */
    private void downFinish(DownloadInfo info) {
        downloadBt.setVisibility(View.GONE);
        String sPath = Environment.getExternalStorageDirectory() + File.separator + GREApp.getContext().getPackageName() + File.separator + "Download" + File.separator + info.getThesaurus_id();
        File file = new File(sPath);
        if (file.exists()) {
            file.delete();
        }
        try {
            ZipUtil.unpack(new File(info.getSavePath()), file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void vDownloadFail(String msg) {
        downloadBt.setText("下载失败");
        downloadBt.setEnabled(true);
    }

    /**
     * 下载进度监听
     *
     * @param read
     * @param contentLength
     * @param done
     */
    @SuppressLint("SetTextI18n")
    @Override
    public void progressChanged(final long read, final long contentLength, boolean done) {
        this.done = done;
        int pro = (int) (((double) read / (double) contentLength) * 100);
        downloadBt.setText("正在下载" + pro + "%");
        if (done) {
            downloadBt.setText("离线语音包已下载");
            downloadBt.setEnabled(false);
        }
    }

    @Override
    public void onAreadyDownload(DownloadInfo info) {
        DowanloadDBManager.getInstance().saveContact(downloadInfo);
        hideLoadDialog();
        downloadBt.setText("离线语音包已下载");
        downloadBt.setEnabled(false);
    }

    @Override
    public void onItemClick(String id, String name) {
        mPresenter.pLastUnit(id, name);
    }

    @Override
    public void onToTest(String id) {
        if (done) {
            AnswerActivity.startThis(this, id);
        } else {
            ToastUtil.getInstance().showNormal(this, "请先下载语音包");
        }
    }

    @Override
    protected void onPause() {
        mPresenter.pPause();
        stopDownService();
        startDownService();
        super.onPause();
    }

    /**
     * 开启下载服务
     */
    private void startDownService() {
        if (!done&&downloadInfo!=null){
            Intent intent = new Intent();
            intent.setAction("com.magic.gre.service.Down");
            intent.setPackage(ChooseUnitActivity.this.getPackageName());
            intent.putExtra("info", downloadInfo);
            startService(intent);
        }
    }

    /**
     * 停止下载服务
     */
    private void stopDownService() {
        Intent intent = new Intent();
        intent.setAction("com.magic.gre.service.Down");
        intent.setPackage(this.getPackageName());
        stopService(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }
}
